<?php
/**
 * Created by PhpStorm.
 * User: 60388
 * Date: 2019/7/8
 * Time: 13:50
 */

//namespace jslife;

//use think\Log;

class Jslife{

    // 请求地址
    private $url;
    // 请求账号
    private $cid;
    // 请求密钥
    private $signKey;
    // 版本
    private $versions = '2';

    public function __construct($type,$cid,$signKey)
    {
        //正式
        if($type == 1){
            $this->url = 'http://www.jslife.com.cn/jsaims';
        }else{
            $this->url = 'http://syx.jslife.com.cn/jsaims';
        }

        $this->cid = $cid;
        $this->signKey = $signKey;
        $this->token = db('car_config')->where('type', 0)->value('token');;
    }

    /**
     *  请求接口 获取返回数据
     * @param $param
     * @return mixed
     * @throws Exception
     */
    public function getDate($param){
        $param = json_encode($param);
        $url = $this->createUrl($param);
        $res = $this->getCurl($url);
//        Log::write('jsurl:'.$url.' res:'.$res);
        $res = json_decode($res, true);
        return $res;
    }


    /**
     *  生成 请求 url
     */
    public function createUrl($param)
    {
        $sn = $this->createSign($param);
        $url = $this->url.'/as?cid=' . $this->cid . '&tn=' . $this->token . '&sn=' . $sn . '&v=' . $this->versions . '&p=' . $param;
        $url = str_replace(" ", "%20",$url);
        return $url;
    }

    /**
     *  生成签名
     */
    public function createSign($param)
    {
        $sn = strtoupper(md5($param . $this->signKey));
        return $sn;
    }

    /**
     * @param $url 请求地址
     * @param int $second 超时时间
     * @return mixed
     */

    public function getCurl($url, $second = 30)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_URL, $url);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        //运行curl
        $data = curl_exec($ch);
        curl_close($ch);
        //返回结果
        if ($data) {
            return $data;
        } else {
            $error = curl_errno($ch);
            throw new \Exception('curl出错'.$error);
        }
    }
}